#include "EyerWASMBlob.hpp"

#include "EyerWASMCommon/EyerWASMEventLoop.hpp"

#include "EyerWASMBlob_OpenEvent.hpp"
#include "EyerWASMBlob_ReadEvent.hpp"

namespace Eyer
{
    EyerWASMBlob::EyerWASMBlob(const std::string & blobUrl)
    {
        m_blobUrl = blobUrl;
    }

    EyerWASMBlob::~EyerWASMBlob()
    {

    }

    int EyerWASMBlob::Open()
    {
        std::shared_ptr<EyerWASMBlob_OpenEvent> event = std::make_shared<EyerWASMBlob_OpenEvent>(m_blobUrl);
        EyerWASMEventLoop::GetInstance()->PutEvent(event);
        std::unique_lock<std::mutex> lck(event->mtx);
        while(!event->isFinish()){
            event->cond.wait_for(lck, std::chrono::seconds(1));
        }
        if(event->isSucc()){
            m_blobKey = event->GetBlobKey();
            m_fileSize = event->GetFileSize();
            return 0;
        }
        return -1;
    }

    bool EyerWASMBlob::IsOpen()
    {
        if(m_fileSize > 0){
            return true;
        }
        return false;
    }

    int EyerWASMBlob::Close()
    {
        return 0;
    }

    int64_t EyerWASMBlob::Read(EyerWASMBuffer & buffer, int64_t pos, int64_t wantLen)
    {
        std::shared_ptr<EyerWASMBlob_ReadEvent> event = std::make_shared<EyerWASMBlob_ReadEvent>(m_blobKey, pos, wantLen);
        EyerWASMEventLoop::GetInstance()->PutEvent(event);
        std::unique_lock<std::mutex> lck(event->mtx);
        while(!event->isFinish()){
            event->cond.wait_for(lck, std::chrono::seconds(1));
        }
        if(event->isSucc()){
            buffer = event->GetBuffer();
            return buffer.GetBufferSize();
        }
        return -1;
    }

    int64_t EyerWASMBlob::GetFileSize()
    {
        return m_fileSize;
    }
}